package com.lnking.lnkingplace.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lnking.common.http.ReturnResult;
import com.lnking.lnkingplace.Util.IdCardUtil;
import com.lnking.lnkingplace.Util.QrcodeUtil;
import com.lnking.lnkingplace.Util.RegexPhoneUtil;
import com.lnking.lnkingplace.Util.UserUtil;
import com.lnking.lnkingplace.mapper.UserMapper;
import com.lnking.lnkingplace.model.dto.user.*;
import com.lnking.lnkingplace.model.entity.Leaders;
import com.lnking.lnkingplace.model.entity.PlaceInfo;
import com.lnking.lnkingplace.model.entity.User;
import com.lnking.lnkingplace.model.request.user.*;
import com.lnking.lnkingplace.service.ILeadersService;
import com.lnking.lnkingplace.service.IPlaceInfoService;
import com.lnking.lnkingplace.service.IUserService;
import com.lnking.starter.export.utils.ExportUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zxq
 * @since 2022-08-18
 */
@Api(tags = "用户模块")
@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * 初始密码
     */
    final String PWD = "123456";
    public static final String MAN = "男";
    public static final String WOMAN = "女";
    public static final String SIGNER = "代签人";
    public static final String SPIT=";";


    @Autowired
    IUserService userService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserUtil userUtil;

    @Autowired
    ILeadersService leadersService;
    @Resource
    IPlaceInfoService placeInfoService;
    @Resource
    QrcodeUtil qrcodeUtil;



    @ApiOperation("添加")
    @PostMapping("add")
    public ReturnResult index(@RequestBody @Valid UserAddRequest params) throws Exception {
        IdCardUtil.isValidatedAllIdcard(params.getIdCard());
        userService.add(params);
        return ReturnResult.success();
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{id}")
    public ReturnResult delete(@PathVariable("id") String id) throws Exception {
        userService.delById(id);
        return ReturnResult.success();
    }

    @ApiOperation("修改用户信息")
    @PostMapping("/update")
    public ReturnResult update(@RequestBody @Valid UserUpdateRequest params) throws Exception {
        IdCardUtil.isValidatedAllIdcard(params.getIdCard());
        User user1 = userService.getBaseMapper().selectById(params.getId());
        if (!user1.getPhone().equals(params.getPhone())) {
            // 防止重复
            QueryWrapper<User> wapper = new QueryWrapper<>();
            wapper.lambda().eq(User::getPhone, params.getPhone());
            Integer integer = userService.getBaseMapper().selectCount(wapper);
            Assert.isTrue(integer == 0, "手机号码不能重复");
        }
        User user = new User();
        BeanUtils.copyProperties(params, user);
        user.setPassword(StringUtils.isNotBlank(user.getPassword()) ? DigestUtils.sha1Hex(user.getPassword()) : null);
        userService.updateById(user);
        PlaceInfo placeInfo = placeInfoService.getBaseMapper().selectById(user.getPlaceId());
        placeInfo.setLinkman(user.getName());
        placeInfo.setLinkmanPhone(user.getPhone());
        placeInfoService.updateById(placeInfo);
        return ReturnResult.success();
    }

    @ApiOperation("获取用户详情")
    @GetMapping("/{id}")
    public ReturnResult getDetail(@PathVariable("id") String id) {
        UserDetailDto user = userService.getUserDetailById(id);
        return ReturnResult.success(user);
    }

    @ApiOperation("重置密码")
    @GetMapping("/reset/{id}")
    public ReturnResult reset(@PathVariable("id") String id) {
        User user = userService.getBaseMapper().selectById(id);
        if (user == null) {
            Leaders leader = leadersService.getBaseMapper().selectById(id);
            leader.setPassword(DigestUtils.sha1Hex(PWD));
            leadersService.getBaseMapper().updateById(leader);
        }else{
            user.setPassword(DigestUtils.sha1Hex(PWD));
            userService.getBaseMapper().updateById(user);
        }
        return ReturnResult.success();
    }


    @ApiOperation("修改密码")
    @PostMapping("/update/password")
    public ReturnResult updatePassword(@RequestBody @Valid UpdatePasswordRequest params) {
        userService.updatePwd(params);
        return ReturnResult.success();
    }

    @ApiOperation("查询用户列表")
    @GetMapping("/list")
    public ReturnResult list(UserSearchRequest params) {
        return ReturnResult.success(userService.getPageList(params));
    }


    @ApiOperation(value = "导出用户信息")
    @GetMapping(value = "/export")
    public void export(UserSearchRequest params, HttpServletResponse response) throws Exception {
        params.setLastCheckTime(null);
        ExportUtils.export((List<UserDto>) userService.pageList(params), response, UserExportDto.class);
    }

    @ApiOperation(value = "导出验证身份号及电话号码")
    @GetMapping("exportUser")
    public void exportUser(UserSearchRequest params, HttpServletResponse response) throws Exception {
        List<UserDto> list = (List<UserDto>) userService.pageList(params);

        List<UserDto> result = list.stream().filter(data -> IdCardUtil.isIdcard(data.getIdCard())
                && RegexPhoneUtil.regexPhone(data.getPhone())).collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(u -> u.getIdCard()))), ArrayList::new));
        ExportUtils.export(result, response, UserExportDto.class);
    }

    @ApiOperation(value = "人员数据概览")
    @GetMapping(value = "/overview")
    public ReturnResult overview() {
        return ReturnResult.success(userMapper.AllStreet());
    }

    @ApiOperation(value = "人员数据概览(街道下)")
    @PostMapping(value = "/overview/street")
    public ReturnResult street(@RequestBody @Valid UserStreetRequest param) {
        return ReturnResult.success(userMapper.street(param));
    }

    @ApiOperation("查询用户列表用于选择代签人")
    @GetMapping("/person/list")
    public ReturnResult personList(String name) {
        return ReturnResult.success(userService.personList(name));
    }


    @ApiOperation("设置代签人")
    @GetMapping("/signer")
    public ReturnResult setSigner( String ids) {
        List<User> users = userService.personList(null);
        if (ids!= null){
            List<String> collect = Arrays.stream(ids.split(SPIT)).collect(Collectors.toList());
            Assert.isTrue(collect.size()<=2,"只能设置两个代签人");
            // 删除之前设置
            for (User user : users) {
                LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
                wrapper.set(User::getUserType, null);
                wrapper.eq(User::getId, user.getId());
                userService.update(wrapper);
            }
            // 写入新的设置
            List<User> userList = userService.getBaseMapper().selectBatchIds(collect);
            for (User user : userList) {
                user.setUserType(SIGNER);
                userService.updateById(user);
            }
        }else{
            // 删除之前设置
            for (User user : users) {
                LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
                wrapper.set(User::getUserType, null);
                wrapper.eq(User::getId, user.getId());
                userService.update(wrapper);

            }
        }

        return ReturnResult.success();
    }


    @ApiOperation("导入")
    @PostMapping(value = "/import")
    public ReturnResult importExcel(@RequestParam("file") MultipartFile file) throws Exception{
        userService.importExcel(file);
        return ReturnResult.success();
    }

    @ApiOperation("写入二维码")
    @PostMapping(value = "/qrcode")
    public ReturnResult qrcode() throws Exception {
        List<User> list = userService.list();
        for (User user : list) {
            user.setQrcode(qrcodeUtil.getQrCodeById(user.getId()));
        }
        userService.updateBatchById(list);
        return ReturnResult.success();
    }

    @ApiOperation("选择点位")
    @PostMapping(value = "/place/choose")
    public ReturnResult placeChoose(String id,String place) throws Exception {
        User byId = userService.getById(id);
        if("工作人员".equals(byId.getType())){
            byId.setAddress(place);
            userService.updateById(byId);
        }else{
            throw new Exception("非工作人员");
        }
        return ReturnResult.success();
    }

}
